const express = require('express');
const router = express.Router();
const {asyncHandler} = require('../utils/sendResult');
const adminService = require("../services/adminServices")
const JwtTool = require("../utils/jwtTool")
const {ValidationError} = require("../utils/customError");

// 用户注册
router.post("/register",asyncHandler(async (req,res,next)=>{
    return  adminService.registerAdmin(req.body)
}))

// 判断用户是否存在
router.get("/isLoginId/:loginId",asyncHandler((req,res,next)=>{
    return adminService.getIsLoginById(req.params.id)
}))

// 用户登录
router.post("/",asyncHandler(async (req,res,next)=>{
    const result = await adminService.loginAdmin(req.body)
    if(!result){
        // 如果不存在 则抛出错误
        throw new ValidationError("账号密码错误")
    }
    JwtTool.generate(res,1000 * 60 * 60 * 24 * 3,result.toJSON())
    return result
}))

// 修改用户信息
router.post("/:id",asyncHandler((req,res,next)=>{
    return adminService.editAdminInfo(req.params.id,req.body)
}))

module.exports = router;
